package com.sicau.socialpracticesystem.config.security;

import com.sicau.socialpracticesystem.entity.po.User;
import com.sicau.socialpracticesystem.util.JwtUtil;
import com.sicau.socialpracticesystem.util.UserContext;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.sicau.socialpracticesystem.common.constant.CommonConstants.CURRENT_USER;

public class TokenAuthenticationFilter extends OncePerRequestFilter {


    private static final String HEADER_STRING = "Authorization";

    private static final String TOKEN_PREFIX = "Bearer";

    private final UserDetailsService userDetailsService;

    public TokenAuthenticationFilter(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @SuppressWarnings("NullableProblems")
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        User currentUser = (User) request.getSession().getAttribute(CURRENT_USER);
        if (currentUser != null) {
            UserContext.put(currentUser);
            filterChain.doFilter(request, response);
            return;
        }

        String token = request.getHeader(HEADER_STRING);
        if (StringUtils.isNotBlank(token) && token.startsWith(TOKEN_PREFIX)) {
            Claims claims = JwtUtil.verifyToken(token.replace(TOKEN_PREFIX, ""));
            if (claims != null) {
                User user = (User) userDetailsService.loadUserByUsername(claims.getSubject());
                SecurityContextHolder.getContext().setAuthentication(new TokenAuthenticationToken(user, user.getPassword(), user.getAuthorities()));
                //放入UserContext供全局获取，在UserContextInterceptor中已经在请求结束后做了移除操作
                UserContext.put(user);
            }
        }
        filterChain.doFilter(request, response);
    }
}
